

// 辅助功能
// 中文转拼音
function ConvertName(chinaName) {
	//获取全写拼音（调用js中方法）        
	let fullName = pinyin.getFullChars(chinaName);
	//获取简写拼音（调用js中方法）
	let easyName = pinyin.getCamelChars(chinaName);
}

// 背景色RGB转十六进制
function RGB2Hex(rgb) {
	let re = rgb.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(","); //利用正则表达袭式去百掉多余的度部分
	let hexColor = "#";
	let hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
	for (let i = 0; i < 3; i++) {
		let r = null;
		let c = re[i];
		const hexAr = [];
		while (c > 16) {
			r = c % 16;
			c = (c / 16) >> 0;
			hexAr.push(hex[r]);
		}
		hexAr.push(hex[c]);
		hexColor += hexAr.reverse().join('');
	}
	return hexColor;
}

// 当前操作组件ID
var ComponentID = '';

// 全局唯一ID
function getId() {
	// 获取毫秒级的时间戳
	let timestamp = new Date().getTime();
	// 获取一个随机数
	let rand = Math.random();
	// 返回固定长度的唯一ID
	// return $.md5(timestamp+""+rand);

	// 测试返回时间戳
	return md5(timestamp + '' + rand);
}

// 左侧点击事件
// 添加空行或提示文本
function add_captions(text = '提示文本', bgcolor = '#ffffff') {
	let captionsId = "captions_" + getId();
	let captions = '<div id="' + captionsId + '" onclick="ComponentAttributes(\'' + captionsId + '\')" class="input-group" '
		+ 'style="padding: 2px;width: 100%;height:24px;background-color: ' + bgcolor + ';">' + text + '</div>';
	$('#phone').append(captions);
}
// 添加单行文本输入框
function add_text() {
	let textId = 'text_' + getId()
	let input = '<div id="' + textId + '" onclick="ComponentAttributes(\'' + textId + '\')" class="input-group disabled">'
		+ '<div class="input-group-prepend">'
		+ '<span class="input-group-text">单行文本输入</span>'
		+ '</div><input class="form-control" type="text" name="' + textId + '" placeholder="文本.."></div>';
	$('#phone').append(input);
}
// 添加多行文本输入框
function add_textarea() {
	let textareaId = 'textarea_' + getId();
	let textarea = '<div id="' + textareaId + '" onclick="ComponentAttributes(\'' + textareaId + '\')" class="input-group">'
		+ '<div class="input-group-prepend">'
		+ '<span class="input-group-text">多行文本输入</span>'
		+ '</div><textarea name="' + textareaId + '" class="form-control" placeholder="文本.."></textarea></div>';
	$('#phone').append(textarea);
}
// 添加数字输入框
function add_number() {
	let numberId = 'number_' + getId();
	let number = '<div id="' + numberId + '" onclick="ComponentAttributes(\'' + numberId + '\')" class="input-group disabled">'
		+ '<div class="input-group-prepend">'
		+ '<span class="input-group-text">数字</span>'
		+ '</div><input class="form-control" type="numer" name="' + numberId + '" placeholder="数字.."></div>';
	$('#phone').append(number);
}
// 添加单选
function add_radio() {
	let radioId = 'radio_' + getId();
	let radio = '<div id="' + radioId + '" onclick="ComponentAttributes(\'' + radioId + '\')" class="form-group"><label>单选</label>'
		+ '<div class="form-check"><input name="' + radioId + '" class="form-check-input" type="radio" value="option1"><label class="form-check-label">单选A</label></div>'
		+ '<div class="form-check"><input name="' + radioId + '" class="form-check-input" type="radio" value="option1"><label class="form-check-label">单选B</label></div>'
		+ '<div class="form-check"><input name="' + radioId + '" class="form-check-input" type="radio" value="option1"><label class="form-check-label">单选C</label></div>'
		+ '<div class="form-check"><input name="' + radioId + '" class="form-check-input" type="radio" value="option2"><label class="form-check-label">单选D</label></div></div>';
	$('#phone').append(radio);
}
// 添加多选
function add_checkbox() {
	let checkboxId = 'checkbox_' + getId();
	let checkbox = '<div id="' + checkboxId + '" onclick="ComponentAttributes(\'' + checkboxId + '\')" class="form-group"><label>多选</label>'
		+ '<div class="form-check"><input name="' + checkboxId + '" class="form-check-input" type="checkbox" value="" ><label class="form-check-label">多选A</label></div>'
		+ '<div class="form-check"><input name="' + checkboxId + '" class="form-check-input" type="checkbox" value="" ><label class="form-check-label">多选B</label></div>'
		+ '<div class="form-check"><input name="' + checkboxId + '" class="form-check-input" type="checkbox" value="" ><label class="form-check-label">多选C</label></div>'
		+ '<div class="form-check"><input name="' + checkboxId + '" class="form-check-input" type="checkbox" value="" ><label class="form-check-label">多选D</label></div></div>';
	$('#phone').append(checkbox);
}

// 组件事件
// 移除组件
function RemoveComponents() {
	// 查找组件
	let component = $("#" + ComponentID);
	console.log("Remove ID: " + ComponentID);
	if (component.length > 0) {
		component.remove();
		$("#attribute").html("<!-- 组件属性 -->");
		console.log("Remove OK");
	} else {
		console.log("Remove fail");
	}
}
// 编辑组件（主要用于打开右侧组件属性）
function ComponentAttributes(ComponentId) {
	// 获取组件类型(特定字段)
	let ComponentType = ComponentId.substring(0, ComponentId.indexOf('_'));
	ComponentID = ComponentId;
	// 组件属性
	let AttributeWindows = $("#attribute");

	switch (ComponentType) {
		case 'captions':
			AttributeWindows.html(EditComponentCaptions());
			console.log("Component is checkbox");
			break;
		case 'text':
			AttributeWindows.html(EditComponentText());
			console.log("Component is Text");
			break;
		case 'textarea':
			AttributeWindows.html(EditComponentText());
			console.log("Component is Textarea");
			break;
		case 'number':
			AttributeWindows.html(EditComponentText());
			console.log("Component is number");
			break;
		case 'radio':
			AttributeWindows.html(EditComponentRadio());
			console.log("Component is radio");
			break;
		case 'checkbox':
			AttributeWindows.html(EditComponentRadio());
			console.log("Component is checkbox");
			break;
		default:
			AttributeWindows.html(EditTemplateTitle());
			console.log("Component is TemplateTitle");
			break;
	}
}

// 编辑提示文本属性
function EditComponentCaptions() {
	let ComponentTips = $("#" + ComponentID).text();
	let bgColor = RGB2Hex($("#" + ComponentID).css("background-color"));

	return '<div class="form-group"><label>提示文本</label>'
		+ '<input id="ComponentTips" oninput="EditComponentCaptionsTips()" class="form-control" type="text" value="' + ComponentTips + '"></div>'
		+ '<label>背景色</label>'
		+ '<input id="CaptionsBgColor" oninput="EditComponentCaptionsBgColor()" class="form-control" type="text" value="' + bgColor + '"></div>'
		+ '<div class="form-group"><button onclick="RemoveComponents()" class="btn btn-danger" type="button">移除组件</button></div>';
}
// 编辑提示文本的文本
function EditComponentCaptionsTips() {
	let ComponentTips = $("#attribute #ComponentTips").val();
	$("#" + ComponentID).text(ComponentTips);
}
function EditComponentCaptionsBgColor() {
	let CaptionsBgColor = $("#attribute #CaptionsBgColor").val()
	$("#" + ComponentID).css("background-color", CaptionsBgColor);
}

// 编辑文本属性(单行文本、多行文本、数字)
function EditComponentText() {
	let ComponentType = ComponentID.substring(0, ComponentID.indexOf('_'));
	let ComponentTitle = $("#" + ComponentID + " .input-group-prepend span").text();
	let ComponentTips = $("#" + ComponentID + " input").attr('placeholder');
	if (ComponentType === "textarea")
		ComponentTips = $("#" + ComponentID + " textarea").attr('placeholder');

	return '<div class="form-group"><label>标题</label>'
		+ '<input id="ComponentTitle" oninput="EditComponentTitle()" class="form-control" type="text" name="title" value="' + ComponentTitle + '"></div>'
		+ '<div class="form-group"><label>提示文本</label>'
		+ '<input id="ComponentTips" oninput="EditComponentTextTips()" class="form-control" type="text" name="tips" value="' + ComponentTips + '"></div>'
		+ '<div class="form-group"><button onclick="RemoveComponents()" class="btn btn-danger" type="button">移除组件</button></div>';
}
// 编辑文本标题(单行文本、多行文本、数字)
function EditComponentTitle() {
	let ComponentType = ComponentID.substring(0, ComponentID.indexOf('_'));
	let ComponentTitle = $("#attribute #ComponentTitle").val();
	switch (ComponentType) {
		case 'text':
			$("#" + ComponentID + " .input-group-prepend span").text(ComponentTitle);
			console.log("Component is Text");
			break;
		case 'textarea':
			$("#" + ComponentID + " .input-group-prepend span").text(ComponentTitle);
			console.log("Component is Textarea");
			break;
		case 'number':
			$("#" + ComponentID + " .input-group-prepend span").text(ComponentTitle);
			console.log("Component is number");
			break;
		case 'radio':
			$("#" + ComponentID + " label").first().text(ComponentTitle);
			console.log("Component is radio");
			break;
		case 'checkbox':
			$("#" + ComponentID + " label").first().text(ComponentTitle);
			console.log("Component is checkbox");
			break;
	}
}
// 编辑文本提示文本(单行文本、多行文本、数字)
function EditComponentTextTips() {
	console.log("This is ComponentTips");
	let ComponentTips = $("#attribute #ComponentTips").val();
	$("#" + ComponentID + " input").attr('placeholder', ComponentTips);
	$("#" + ComponentID + " textarea").attr('placeholder', ComponentTips);
}

// 编辑单(多)选组件属性
function EditComponentRadio() {
	let ComponentTitle = $("#" + ComponentID + " label").first().text();
	let html = '<div class="form-group"><label>标题</label>'
		+ '<input id="ComponentTitle" oninput="EditComponentTitle()" class="form-control" type="text" name="title" value="' + ComponentTitle + '"></div>'
		+ '<div id="EditRadio" class="form-group"><label>选项：</label>';
	$("#" + ComponentID + " .form-check label").each(function () {
		console.log($(this).text());
		html += '<div class="form-check"><label class="form-check-label">选项 &nbsp;&nbsp; </label>'
			+ '<input oninput="EditComponentRadioOption()" class="form-check-input" type="text" value="' + $(this).text() + '"></div>'
	});

	html += '</div><div class="form-group">';
	html += '<button onclick="EditComponentRadioMinus()" class="btn btn-purple" type="button">删除选项</button>  ';
	html += '<button onclick="EditComponentRadioAdd()" class="btn btn-info" type="button">添加选项</button>  ';
	html += '<button onclick="RemoveComponents()" class="btn btn-danger" type="button">移除组件</button></div>';
	return html;
}
// 编辑单(多)选组件内容
function EditComponentRadioOption() {
	// 获取组件
	let Comments = $("#" + ComponentID + " .form-check label");
	// 获取属性
	let EditRadioOption = $("#attribute #EditRadio input");
	// 修改组件的属性
	EditRadioOption.each(function (i) {
		$(Comments[i]).text($(this).val());
	})
}
// 编辑单(多)选组件选项(新增选项)
function EditComponentRadioAdd() {

	// 复制最后一个选项来添加一个新的选项
	$("#" + ComponentID).append('<div class="form-check">'+ $("#" + ComponentID + " .form-check:last").html()+'</div>');
	// 重新执行获取组件内容以刷新属性
	ComponentAttributes(ComponentID);
}
// 编辑单(多)选组件选项(删除选项)
function EditComponentRadioMinus() {
	// <input name="" class="form-check-input" type="checkbox" value=""><label class="form-check-label">多选C</label></div>
	$("#" + ComponentID + " .form-check:last").remove()
	// 重新执行获取组件内容以刷新属性
	ComponentAttributes(ComponentID);
}

// 编辑任务模板名称
function EditTemplateTitle() {
	return '<div class="form-group"><label>任务模板名称</label>'
		+ '<input id="TemplateTitleText" oninput="upTemplateTitle()" class="form-control" type="text" value="' + $("#templateTitle h4").text() + '"></div>';
}
// 修改模板标题
function upTemplateTitle() {
	$("#templateTitle h4").text($("#TemplateTitleText").val());
}

// 取组件名称
function getComponentTitle(componentId){

	let type = componentId.substring(0, componentId.indexOf("_"))

	if (type === 'text' || type === "number" || type === "textarea")
		return $("#"+componentId +" div span").text()
	else if(type === "radio" || type === "checkbox")
		return $("#"+componentId +" label").first().text()
}

// 获取所有组件字段及ID
function getTemplateFields() {
	let TemplateFields = [];
	// 解析模板内容
	$("#phone [id]").each(function () {
		let componentId = $(this).attr('id')
		// 若不是提示语则解析其标题
		if ("captions" !== componentId.substring(0, componentId.indexOf("_"))) {
			TemplateFields.push({"key":componentId, "value":getComponentTitle(componentId)})
		}
	});
	return JSON.stringify(TemplateFields);
}

// 保存模板按钮点击事件
function saveTemplate() {
	// 模板标题
	let TemplateName = $("#templateTitle h4").text();
	// 填报字段列表
	let TemplateFields = getTemplateFields();
	// 填报模板HTML
	let TemplateContext = $("#phone").html();

	if (TemplateFields === ""){
		swal({title: "不能保存，您还没有设置任何字段！！！", icon: "error", button: {
				text: "OK",
				value: true,
				visible: true,
				className: "btn btn-danger",
				closeModal: true,
			}
		});
		return false;
	}

	console.log("模板名称", TemplateName)
	console.log("模板字段：", TemplateFields);
	console.log("模板内容：", TemplateContext);

	lightyear.loading('show');
	saveTemplateAjax(TemplateName, TemplateFields, TemplateContext);

}

function upTemplate(TemplateId) {
	if (!TemplateId){

		lightyear.notify('遇到错误操作，我怀疑你在破解我，所有我要把你送去登录~', 'danger', 3000);
		location.href = "/";
		return false;
	}else {

		// 模板标题
		let TemplateName = $("#templateTitle h4").text();
		// 填报字段列表
		let TemplateFields = getTemplateFields();
		// 填报模板HTML
		let TemplateContext = $("#phone").html();

		if (TemplateFields === ""){
			lightyear.notify('你没有设置任何字段，不允许保存空模板', 'danger', 3000);
			return false;
		}else {
			//
			// console.log("模板ID：", TemplateId);
			// console.log("模板名称：", TemplateName)
			// console.log("模板字段：", TemplateFields);
			// console.log("模板内容：", TemplateContext);

			lightyear.loading('show');
			saveTemplateAjax(TemplateName, TemplateFields, TemplateContext, TemplateId, "UpdateTemplate");
		}
	}
}

function saveTemplateAjax(TemplateName, TemplateFields, TemplateContext, TemplateId = null, url = "SaveTemplate") {
	$.ajax({
		type: "POST",
		url: "/Template/" + url,
		dataType: "json",
		data: {
			"templateId": TemplateId,
			"templateName": TemplateName,
			"fields": TemplateFields,
			"context": TemplateContext
		},
		success: function (data, status) {
			console.log(data)
			lightyear.loading('hide');
			if (status === "success") {
				if (data.code === 200){
					lightyear.notify('成功了，页面即将自动跳转~', 'success', 1000);
					setTimeout(function () {
						location.href = "/Template/List";
					}, 3000)

				} else{
					console.log("后端拒绝")
					lightyear.notify(data.msg, 'danger', 3000);
				}
			}else{
				console.log("网络问题")
				lightyear.notify('网络不可用，请稍候再试！！！', 'danger', 3000);
			}
		},
		error: function (xhr, errorText, errorType) {
			lightyear.loading('hide');
			lightyear.notify('服务器错误，请稍后再试~', 'danger', 2000);
		},
		complete: function () {
			//do something
		}
	})
}